package com.itheima.health.timing;


import com.itheima.health.service.SetMealService;
import com.itheima.health.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class OssCleanTiming {

    @Resource
    private AliOssUtil aliOssUtil;

    @Resource
    private SetMealService setmealService;

    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行一次 删除未使用的图片
    public void cleanup() {
        log.info("凌晨2点 ===> 开始执行定时任务！！");
        // 获得桶中的key
        Map<String, String> ossKeyMap = aliOssUtil.listAllFiles();
        // 查询套餐表中所有图片 并获取图片name
        List<String> imageKeys = setmealService.findAllImageKeys();
        Set<String> imageKeySet = null;
        try {
            imageKeySet = imageKeys.stream()
                    .filter(Objects::nonNull) // 过滤掉空值
                    .map(imageKey -> imageKey.substring(imageKey.lastIndexOf("/") + 1))
                    .collect(Collectors.toSet());
        } catch (Exception e) {
            log.error("imageKeys.stream().map(imageKey -> imageKey.substring(imageKey.lastIndexOf(\"/\") + 1)) error:{}", e);
            e.printStackTrace();
        }
        // 遍历key
        int count = 0;
        for (String key : ossKeyMap.keySet()) {
            String name = ossKeyMap.get(key);
            if (!imageKeySet.contains(name)) {
                // 删除key
                aliOssUtil.deleteFile(key);
                count ++;
            }
        }
        log.info("凌晨2点 ===> 定时任务执行完毕！删除除本地不存在户图片：{} 张！ 删除完成", count);
    }
}
